import axios, { AxiosRequestConfig } from 'axios'

const baseURL = import.meta.env.VITE_BASE_URL
// 创建实例
const instance = axios.create({
	baseURL,
	headers: {
		Accept: '*/*',
		'Content-Type': 'application/json;charset=UTF-8'
	},
	timeout: 30000,
	withCredentials: true
})

// 请求拦截
instance.interceptors.request.use(
	(config) => {
		if (config.headers) {
			config.headers.token = ''
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// 响应拦截
instance.interceptors.response.use(
	(response) => {
		if (response.status === 200) {
			if (response.data.code !== 0) {
				return Promise.reject(response.data)
			}
			return Promise.resolve(response.data)
		}
		return Promise.reject(response)
	},
	(error) => {
		const { response } = error
		if (response && response.data) {
			return Promise.reject(error)
		}
		return Promise.reject(error)
	}
)

export const request = <T>(config: AxiosRequestConfig): Promise<T> => {
	return instance.request(config)
}

export default instance
